package com.wq.interceptors;


import io.jsonwebtoken.Claims;
import com.wq.handlers.BaseContext;
import com.wq.utils.JwtUtil;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

/**
 * @author wq
 */
@Slf4j
@Component
public class AuthorizationInterceptor implements HandlerInterceptor {
    @Resource
    private JwtUtil jwtUtil;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        log.info("拦截器生效了...");
        
        // 内部服务调用放行（根据ID查询用户信息）
        String requestURI = request.getRequestURI();
        if (requestURI.matches(".*/user/\\d+")) {
            log.info("内部服务调用，放行");
            return true;
        }
        
        String token = request.getHeader("Authorization");
        log.info("token:{}",token);
        if(token==null){
            log.info("token丢失...");
            return false;
        }
        token=token.replace("Bearer ","");
        if(!jwtUtil.validateToken(token)){
            log.info("token已过期...");
            return false;
        }
        Claims claims = jwtUtil.parseToken(token);
        Long id = claims.get("id", Long.class);

        // 存入线程变量
        BaseContext.setCurrentId(id);

        return true;
    }
}
